# Create your views here.
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse, HttpResponseNotFound
from django.utils import simplejson
from django.contrib.auth.decorators import login_required

from models import RegistrationProfile
from utils import cleanTagSoup,find_first_occurance_excerpt



@login_required
def search_patients_on_medical_record(request, extra_context = None):
    try:
        matched_user_profiles = RegistrationProfile.objects.filter(medical_record__icontains = request.REQUEST.get('query',"")) 
    except:
        import traceback
        print repr(traceback.print_exc())
        resp = dict(success=False, errors="Server Error")
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    else:
        startIndex = int(request.REQUEST.get('start',0))
        endIndex = startIndex + int(request.REQUEST.get('limit', 10))
        paged_matched_user_profiles = matched_user_profiles[startIndex:endIndex]
        resp = dict(success=True, totalCount=len(matched_user_profiles), 
                   data=[dict(medical_record_id=profile.user.id, medical_record=find_first_occurance_excerpt(cleanTagSoup(profile.medical_record), request.REQUEST.get('query',"")), last_login=profile.user.last_login, patient_name = profile.user.username) \
                            for profile in paged_matched_user_profiles])
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))